//
//  ManufacturerViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/27.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import MJRefresh

//  厂商直销  和新品推荐

class ManufacturerViewController: BaseViewController {
    
    var dataArray = [SiteGoodsModel]()
    
    var manufacturerArray = [FireSiteModel]()
    
    var index = 0
    
    var page = 1
    
//    var nextid = 0 // 下一家
//    var manufactureID = 0
    
    var headerUrl = ""
    
    var isNewGoodsRecommend = false
    
    @IBOutlet weak var bottomViewHeight: NSLayoutConstraint!
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var bottomView: UIView!
    
    var headerImg:UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let flowLayout = UICollectionViewFlowLayout()
        let height = 75.5 + ((UIScreen.ScreenWidth - 30) * 0.5)/(160/130)
        flowLayout.itemSize = CGSize.init(width: (UIScreen.ScreenWidth - 30) * 0.5, height: height)
        flowLayout.scrollDirection = .vertical
        flowLayout.headerReferenceSize = CGSize.init(width: UIScreen.ScreenWidth, height: (UIScreen.ScreenWidth - 24)/(352/180) + 28)
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 12, 0, 12)
        flowLayout.minimumLineSpacing = 2
        flowLayout.minimumInteritemSpacing = 5
        
        self.collectionView.setCollectionViewLayout(flowLayout, animated: true)
        self.collectionView.showsVerticalScrollIndicator = false
        self.collectionView.register(UICollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionHeader")
        
        if !self.isNewGoodsRecommend {
            self.bottomView.setShadow(color: "000000", offset: CGSize.init(width: 0, height: -1), radius: 0.5, opacity: 0.02)
            self.headerUrl = self.manufacturerArray[index].img
        }
        
        self.collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] in
            self?.page = 1
            if (self?.isNewGoodsRecommend)! {
                self?.getIndexNew()
            }else{
                self?.getIndexManufactors()
            }
        })
        
        self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: { [weak self] in
            self?.page = (self?.page)! + 1
            if (self?.isNewGoodsRecommend)! {
                self?.getIndexNew()
            }else{
                self?.getIndexManufactors()
            }
        })
        
        PKhud.show()
        if self.isNewGoodsRecommend {
            self.title = "新品推荐"
            self.bottomViewHeight.constant = 0
            self.getIndexNew()
        }else{
            self.title = self.manufacturerArray[index].name
            self.getIndexManufactors()
        }
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: 上一家
    @IBAction func upButtonClick(_ sender: UIButton) {
//        self.backBarButtonMethon()
        self.page = 1
        self.index = self.index - 1
        if self.index < 0 {
            self.index = self.manufacturerArray.count - 1
        }
        self.updateHeaderAndTitle()
        self.getIndexManufactors()
    }
    
    
    // MARK:下一家
    @IBAction func nextButtonClick(_ sender: UIButton) {
        self.page = 1
        self.index = self.index + 1
        if self.index == self.manufacturerArray.count {
            self.index = 0
        }
        self.updateHeaderAndTitle()
        self.getIndexManufactors()
    }
    
    func updateHeaderAndTitle(){
        self.title = self.manufacturerArray[index].name
        self.headerUrl = self.manufacturerArray[index].img
    }
    
    
    
    // MARK:新品推荐
    func getIndexNew(){
        
        HttpRequest.requestData(.post, URLString: Api.indexNnew.rawValue, parameters: ["pageSize":10,"pageNum":page]) { (result) in
            if result["msg"] as! String == "success"{
                PKhud.hiden()
                self.collectionView.mj_header.endRefreshing()
                self.collectionView.mj_footer.endRefreshing()
                if let array = [SiteGoodsModel].deserialize(from: result["data"] as? [Any]) as? [SiteGoodsModel]{
                    if self.page == 1 {
                        self.dataArray = array
                    }else{
                        self.dataArray = self.dataArray + array
                    }
                    
                    if array.count < 10 {
                        self.collectionView.mj_footer.endRefreshingWithNoMoreData()
                    }
                    self.getNewGoodsBanner()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    func getNewGoodsBanner(){
        HttpRequest.requestData(.post, URLString: Api.banner.rawValue, parameters: ["position":2]) { (result) in
            if result["msg"] as! String == "success"{
                if let dic = result["data"] as? postParameters {
                    self.headerUrl = dic["img"] as! String
                    self.collectionView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    
    // MARK:厂家
    func getIndexManufactors(){
        HttpRequest.requestData(.post, URLString: Api.manufactorGoods.rawValue, parameters: ["manufactorId":self.manufacturerArray[index].id,"pageNum":self.page,"pageSize":10]) { (result) in
            self.collectionView.mj_header.endRefreshing()
            self.collectionView.mj_footer.endRefreshing()
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                if let array = [SiteGoodsModel].deserialize(from: result["data"] as? [Any]) as? [SiteGoodsModel] {
                    if self.page == 1 {
                        self.dataArray = array
                    }else{
                        self.dataArray = self.dataArray + array
                    }
                    if array.count < 10 {
                        self.collectionView.mj_footer.endRefreshingWithNoMoreData()
                    }
                    self.collectionView.reloadData()
                }
                
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
}

extension ManufacturerViewController:UICollectionViewDelegate,UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GoodsCollectionViewCell", for: indexPath) as! GoodsCollectionViewCell
        cell.reload(withModel: self.dataArray[indexPath.row])
        cell.loginClosure = { [weak self] in
            if (UIApplication.shared.delegate as! AppDelegate).isShowLogin == false {
                (UIApplication.shared.delegate as! AppDelegate).isShowLogin = true
                PKhud.showText(text: "请先登录~")
                let vc = Utils.instantiateInitialViewControllerWith(storyBoardName:"Main", identitier: "LoginViewController") as! LoginViewController
                vc.hidesBottomBarWhenPushed = true
                self?.present(UINavigationController.init(rootViewController: vc), animated: true, completion: nil)
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        var header : UICollectionReusableView?
        if kind == UICollectionElementKindSectionHeader {
            header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionHeader", for: indexPath)
            let shadowLayer = CALayer()
            shadowLayer.frame = CGRect.init(x: 12, y: 15, width: UIScreen.ScreenWidth - 24, height: (UIScreen.ScreenWidth - 24)/(352/180))
            shadowLayer.backgroundColor = UIColor.backgroundColor.cgColor
            shadowLayer.shadowColor = UIColor.init(hexColor: "#465138").cgColor
            shadowLayer.shadowOffset = CGSize.init(width: 1.2, height: 1.7)
            shadowLayer.shadowOpacity = 0.15
            shadowLayer.cornerRadius = 15
            shadowLayer.shadowRadius = 3
            header?.layer.addSublayer(shadowLayer)
            
            self.headerImg = UIImageView.init()
            self.headerImg.my_setImage(url: self.headerUrl, placeholder: "img_placeholder_2")
            self.headerImg.frame = shadowLayer.frame
            self.headerImg.setCornerRadio(radio: 15, isMask: true)
            header?.addSubview(self.headerImg)
        }
        return header!
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.dataArray[indexPath.row]
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "GoodsDetailViewController") as! GoodsDetailViewController
        ctrl.goodsID = model.id
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
}


















